package com.sun.utils;

import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import darabonba.core.client.ClientOverrideConfiguration;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * 短信发送工具类
 */
public class SMSUtils {

	/**
	 * 发送短信
	 * @param signName 签名
	 * @param templateCode 模板
	 * @param phoneNumbers 手机号
	 * @param param 参数
	 * @return
	 */
	public static boolean sendMessage(String signName, String templateCode, String phoneNumbers, String param){
		StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
				.accessKeyId("LTAI5tS5thV7fhQZqEBQnUuU")
				.accessKeySecret("MIJZSxKLPGTlwniTsUouV8RKQZMPie")
				//.securityToken("<your-token>") // use STS token
				.build());
		AsyncClient client = AsyncClient.builder()
				.region("cn-hangzhou")
				.credentialsProvider(provider)
				.overrideConfiguration(
						ClientOverrideConfiguration.create()
								.setEndpointOverride("dysmsapi.aliyuncs.com")
						//.setReadTimeout(Duration.ofSeconds(30))
				)
				.build();
		SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
				.signName(signName)
				.templateCode(templateCode)
				.phoneNumbers(phoneNumbers)
				.templateParam("{\"code\":\""+param+"\"}")
				// Request-level configuration rewrite, can set Http request parameters, etc.
				// .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders()))
				.build();
		try {
			CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
			SendSmsResponse resp = response.get();
		} catch (InterruptedException | ExecutionException e) {
			e.printStackTrace();
			return false;
		}
		System.out.println("短信发送成功");
		client.close();
		return true;

//		DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAI5tS5thV7fhQZqEBQnUuU", "MIJZSxKLPGTlwniTsUouV8RKQZMPie");
//		IAcsClient client = new DefaultAcsClient(profile);
//
//		SendSmsRequest request = new SendSmsRequest();
//		request.setSysRegionId("cn-hangzhou");
//		request.setPhoneNumbers(phoneNumbers);
//		request.setSignName(signName);
//		request.setTemplateCode(templateCode);
//		request.setTemplateParam("{\"code\":\""+param+"\"}");
//		try {
//			SendSmsResponse response = client.getAcsResponse(request);
//			System.out.println("短信发送成功");
//		}catch (ClientException e) {
//			e.printStackTrace();
//		}
	}

}
